package com.ethereal.petmanagement.util;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.Map;

public class BeanUtil {

    public static <T> T mapRequestToBean(HttpServletRequest request, Class<T> clazz) {
        try {
            T bean = clazz.getDeclaredConstructor().newInstance();
            Map<String, String[]> paramMap = request.getParameterMap();

            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                String fieldName = field.getName();

                if (paramMap.containsKey(fieldName)) {
                    String value = paramMap.get(fieldName)[0];
                    if (value == null || value.trim().isEmpty()) continue;

                    Object convertedValue = convertToFieldType(field.getType(), value);
                    field.set(bean, convertedValue);
                }
            }

            return bean;
        } catch (Exception e) {
            throw new RuntimeException("参数映射失败: " + e.getMessage(), e);
        }
    }

    private static Object convertToFieldType(Class<?> type, String value) {
        if (type == String.class) {
            return value;
        } else if (type == int.class || type == Integer.class) {
            return Integer.parseInt(value);
        } else if (type == long.class || type == Long.class) {
            return Long.parseLong(value);
        } else if (type == java.math.BigInteger.class) {
            return new java.math.BigInteger(value);
        } else if (type == byte.class || type == Byte.class) {
            return Byte.parseByte(value);
        } else if (type == boolean.class || type == Boolean.class) {
            return Boolean.parseBoolean(value);
        } else if (type == java.sql.Timestamp.class) {
            return Timestamp.valueOf(value + (value.length() == 10 ? " 00:00:00" : ""));
        } else if (type == java.sql.Date.class) {
            return java.sql.Date.valueOf(value);
        }
        return null;
    }
}
